package com.im.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.im.app.model.ServeGroupUser;
import com.im.app.model.*;
import com.im.app.service.*;
import com.im.app.utils.*;
import com.im.app.utils.uuid.IdUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.server.JimServerAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping(value = "/admin")
public class AdminController extends BaseController{

    @Resource
    private ICodeService codeService;
    @Resource
    private IUserService userService;
    @Resource
    private IAdminService adminService;
    @Autowired
    private VisitorAvatarService visitorAvatarService;

    @Resource
    private IServeGroupService serveGroupService;
    @Resource
    private IFlowRecordLogsService flowRecordService;

    @Resource
    private IPersonhostService personhostService;

    @GetMapping(value ="/getAdminInfo")
    public ResponseResult<Object> getAdminInfo(@RequestHeader String token){

        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }

        Admin admin1 = adminService.selectAdminById(admin.getId());
        admin1.setToken(token);
        return Response.makeOKRsp(admin1);
    }

    @PostMapping(value ="/addCode")
    public ResponseResult<Object> addCode(Integer day,Integer count,String marks,String type,@RequestHeader String token){

        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        admin = adminService.selectAdminById(admin.getId());

        int money = admin.getTotalMoney() -  admin.getSettlementMoney();
        if (money <= 0){
            return Response.makeErrRsp("当前余额不足");
        }
        int cMoney = count * admin.getPrice();
        if (money < cMoney){
            return Response.makeErrRsp("当前余额不足");
        }
        if (!"uselogin".equals(type) && !"usexufei".equals(type) && !"useduli".equals(type)){
            return Response.makeErrRsp("类型不对");
        }

        List<Code> codes = new ArrayList<>();
        List<User> users = new ArrayList<>();
        List<FlowRecordLogs> records = new ArrayList<>();
        String su = "-LG";
        if ("usexufei".equals(type)){
            su = "-XF";
        }else if ("useduli".equals(type)){
            su = "-DL";
        }
        for (int i = 0; i < count; i++) {
            VisitorAvatar visitorAvatar = getAvatar(); //生成用户
            if (visitorAvatar == null) {
                return Response.makeErrRsp("卡密生成失败-->没有可用用户");
            }
            String kimicode=RandomNum.randomdaxie(10)+su;
            Code code = new Code();
            code.setAddtime(new Date());
            code.setKamicode(kimicode);
            code.setIssold("sold");
            code.setKamistatus("nouse");
            code.setDays(day);
            code.setBeizhu(marks);
            code.setKamitype(type);
            code.setAdminId(admin.getId());
            code.setPrice(admin.getPrice());
            code.setType(admin.getType());
            code.setCreateUser(admin.getName());
            codes.add(code);
            Integer cM = admin.getPrice();
            if (!type.equals("useduli")){
                cM = day * admin.getPrice();
            }
            admin.setSettlementMoney(admin.getSettlementMoney() + cM);
            admin.setUseMoney(admin.getUseMoney() + cM);
            FlowRecordLogs record = FlowRecordLogs.createRecord(admin, "添加"+getType(type)+"卡密",   kimicode + " x " + day + "天");
            records.add(record);
            if("uselogin".equals(type)){//注册用户
                String nickname = visitorAvatar.getName();
                String userId = IdUtils.simpleUUID();
                String avatar = visitorAvatar.getAvatar();
                User user = new User();
                user.setUserId(userId);
                user.setName(nickname);
                user.setAvatar(avatar);
                user.setKamicode(kimicode);
                user.setAppMangerLevel(3);
                user.setStatus(1);
                user.setActStatus(0);
                user.setAdminId(admin.getId());
                user.setCreateTime(new Date());
                user.setCreateUser(admin.getName());
                users.add(user);
            }
        }
        boolean result = codeService.saveBatch(codes);
        if (result){
            userService.saveBatch(users);
            int a = adminService.updateAdminUseMoney(admin);
            flowRecordService.batchInsert(records);
            return Response.makeOKRsp(admin);
        }
        return Response.makeErrRsp("卡密生成失败");
    }

    @PostMapping(value = "/renew")
    public ResponseResult<Object> renew(@RequestBody Renew renew,@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        admin = adminService.selectAdminById(admin.getId());

        if (renew.getDay() <= 0){
            return Response.makeErrRsp("续费时长不能为空");
        }

        if (renew.getCodes().size() <= 0){
            return Response.makeErrRsp("续费卡密不能为空");
        }
        int money = admin.getTotalMoney() - admin.getUseMoney();
        int uM = renew.getDay() * renew.getCodes().size() * admin.getPrice();
        if (money <= 0 || money < uM){
            return Response.makeErrRsp("当前可用余额不足");
        }
        List<User> users = new ArrayList<>();
        List<Code> codes = new ArrayList<>();
        List<FlowRecordLogs> records = new ArrayList<>();
        for (int i = 0; i < renew.getCodes().size(); i++) {
            String code = renew.getCodes().get(i);
            User user = userService.getUserBykamiCode(code);
            Code code1 = codeService.getCodeByKamicode(code);
            if (user != null && code1 != null && code1.getKamitype().equals(Constants.USELOGIN)){
                if (code1.getKamistatus().equals(Constants.KAMINOUSE)){
                    return Response.makeErrRsp("卡密"+code+"未激活");
                }else if (code1.getKamistatus().equals(Constants.DISABLE)){
                    return Response.makeErrRsp("卡密"+code+"已停用");
                }
                Date nowTime = new Date();
                Date startDate = user.getEndTime();
                if (startDate.getTime() < nowTime.getTime()) {
                    startDate = nowTime;
                }
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(startDate);
                rightNow.add(Calendar.DATE, renew.getDay());
                user.setEndTime(rightNow.getTime());
                code1.setEndTime(rightNow.getTime());
                codes.add(code1);
                users.add(user);
                int m = renew.getDay() * admin.getPrice();
                admin.setUseMoney(admin.getUseMoney() + m);
                admin.setSettlementMoney(admin.getSettlementMoney() + m);
                FlowRecordLogs record = FlowRecordLogs.createRecord(admin, "续费卡密", code + " + " + renew.getDay() + "天");
                records.add(record);
            }else {
                return Response.makeErrRsp("续费卡密"+code+"有误");
            }
        }
        flowRecordService.batchInsert(records);
        userService.updateBatchById(users);
        codeService.updateBatchById(codes);
        adminService.updateAdminUseMoney(admin);
        return Response.makeOKRsp(admin);
    }

    @GetMapping(value = "/getCodeList")
    public ResponseResult<Object> getCodeList(QueryCode queryCode,@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        Page<Code> page = new Page<>();
        page.setCurrent(queryCode.getPage());
        page.setSize(queryCode.getSize());
        QueryWrapper<Code> qw = new QueryWrapper<>();
        qw.eq("admin_id",admin.getId());
        if (!StringUtils.isEmpty(queryCode.getOrderType()) && !StringUtils.isEmpty(queryCode.getOrderName())){
            if (queryCode.getOrderType().equals("asc")){
                qw.orderByAsc(queryCode.getOrderName());
            }else {
                qw.orderByDesc(queryCode.getOrderName());
            }
        }else {
            qw.orderByDesc("addtime");
        }

        if (!StringUtils.isEmpty(queryCode.getCode())){
            qw.eq("kamicode",queryCode.getCode());
        }

        if (!StringUtils.isEmpty(queryCode.getType())){
            qw.eq("kamitype",queryCode.getType());
        }

        if (!StringUtils.isEmpty(queryCode.getStatus())){
            if (queryCode.getStatus().equals("disable")){
                qw.eq("disable",1);
            }else {
                qw.eq("kamistatus",queryCode.getStatus());
                qw.eq("disable",0);
            }
        }

        Page<Code> result = codeService.page(page, qw);
        return Response.makeOKRsp(result);
    }

    @GetMapping(value = "/getRecord")
    public ResponseResult<Object> getRecord(int pageNum,int pageSize,@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        FlowRecordLogs recordLogs = new FlowRecordLogs();
        recordLogs.setAdminId(admin.getId());

        Page<FlowRecordLogs> page = flowRecordService.selectFlowRecordLogsList(recordLogs, pageNum , pageSize);
        return Response.makeOKRsp(page);
    }

    @GetMapping(value = "/codeDetails")
    public ResponseResult<Object> codeDetails(String code,@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }

        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Code> qw = new QueryWrapper<>();
        qw.eq("admin_id",admin.getId());
        qw.eq("kamicode",code);
        Code code1 = codeService.getOne(qw);
        if (code1 == null){
            return Response.makeErrRsp("卡密有误");
        }
        map.put("code",code1);
        if (code1.getKamistatus().equals("inuse")){
            if ("uselogin".equals(code1.getKamitype())){
                User user = userService.getUserBykamiCode(code);
                map.put("user",user);
            }else {
                User user = userService.getUserBykamiCode(code1.getUserId());
                map.put("user",user);
                if ("usexufei".equals(code1.getKamitype())){

                }else if ("useduli".equals(code1.getKamitype())){
                    Personhost host = personhostService.getPersonHostByKaMiCode(code);
                    map.put("host",host);
                }
            }
        }


        return Response.makeOKRsp(map);
    }


    @GetMapping(value = "/disable")
    public ResponseResult<Object> disable(String code,@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        QueryWrapper<Code> qw = new QueryWrapper<>();
        qw.eq("admin_id",admin.getId());
        qw.eq("kamicode",code);
        Code one = codeService.getOne(qw);
        if (one == null){
            return Response.makeErrRsp("操作失败");
        }
        one.setDisable(one.getDisable() == 0 ? 1 : 0);
        codeService.updateById(one);

        if ("uselogin".equals(one.getKamitype())){
            User user = userService.getUserBykamiCode(code);
            if (user != null){
                user.setStatus(one.getDisable() == 0 ? 1 : 0);
                userService.updateById(user);
                List<ImChannelContext> channelContexts = JimServerAPI.getByUserId(user.getUserId());
                for (ImChannelContext channelContext: channelContexts) {
                    String token1 = channelContext.getSessionContext().getImClientNode().getUser().getToken();
                    try {
                        JedisTemplate.me().delKey(token1);
                    } catch (Exception ignored) {

                    }
                }
            }
        }

        return Response.makeOKRsp();
    }

    @GetMapping(value = "/getUserList")
    public ResponseResult<Object> getUser(Integer pageNum,Integer pageSize,@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        if (pageNum == null){
            pageNum = 1;
        }
        if (pageSize == null){
            pageSize = 10;
        }
        Page<User> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("admin_id",admin.getId());
        qw.orderByDesc("create_time");
        Page<User> result = userService.page(page, qw);
        return Response.makeOKRsp(result);
    }

    @GetMapping(value = "/getGroupUserList")
    public ResponseResult<Object> getGroupUserList(Integer groupId,@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        List<User> users = adminService.selectGroupUserList(groupId);
        return Response.makeOKRsp(users);
    }

    @PostMapping(value = "/addGroupUser")
    public ResponseResult<Object> addGroupUser(@RequestBody List<ServeGroupUser> groupUsers, @RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        int result = adminService.addGroupUsers(groupUsers);
        if (result > 0){
            return Response.makeOKRsp();
        }else {
            return Response.makeErrRsp("操作失败");
        }
    }

    @GetMapping(value = "/deletedGroupUser")
    public ResponseResult<Object> deletedGroupUser(String ids, @RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        int result = adminService.deletedGroupUsers(ids);
        if (result > 0){
            return Response.makeOKRsp();
        }else {
            return Response.makeErrRsp("操作失败");
        }
    }


    @GetMapping(value = "/getGroups")
    public ResponseResult<Object> getGroups(@RequestHeader String token){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        ServeGroup serveGroup = new ServeGroup();
        serveGroup.setAdminId(admin.getId());
        List<ServeGroup> serveGroups = serveGroupService.selectServeGroupList(serveGroup);
        return Response.makeOKRsp(serveGroups);
    }

    @PostMapping(value = "/addGroup")
    public ResponseResult<Object> addGroup(@RequestHeader String token,ServeGroup group){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        group.setAdminId(admin.getId());
        int i = serveGroupService.insertServeGroup(group);
        if (i > 0){
            return Response.makeOKRsp();
        }else {
            return Response.makeErrRsp("添加失败");
        }
    }

    @PostMapping(value = "/updateGroup")
    public ResponseResult<Object> updateGroup(@RequestHeader String token,ServeGroup group){
        Admin admin = getAdmin(token);
        if (admin == null){
            return Response.makeRsp(401,"登录已过期");
        }
        group.setAdminId(admin.getId());
        int i = serveGroupService.updateServeGroup(group);
        if (i > 0){
            return Response.makeOKRsp();
        }else {
            return Response.makeErrRsp("添加失败");
        }
    }



    private String getType(String type){
        if ("uselogin".equals(type)){
            return FlowRecordLogs.CREATE_USER;
        }else if ("useceshi".equals(type)){
            return FlowRecordLogs.TEST;
        }else if ("useduli".equals(type)){
            return FlowRecordLogs.HOST;
        }else if ("usexufei".equals(type)){
            return FlowRecordLogs.RENEW;
        }
        return type;
    }

    private VisitorAvatar getAvatar() {
        VisitorAvatar visitorAvatar = visitorAvatarService.getVisitorAvatarByRandom();
        if (visitorAvatar != null) {
            visitorAvatar.setUCount(visitorAvatar.getUCount() + 1);
            visitorAvatarService.updateById(visitorAvatar);
            return visitorAvatar;
        }
        return null;
    }
}
